import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '../views/Films.vue' // @符号永远指向src的绝对路径
import Nowplaying from '@/views/films/Nowplaying'
import Comingsoon from '@/views/films/Comingsoon'
import Cinemas from '@/views/Cinemas'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import Login from '@/views/Login'
import City from '@/views/City'

Vue.use(VueRouter) // 注册路由插件

// 配置表
const routes = [
  {
    path: '/films',
    component: Films,
    children: [{
      path: '/films/nowplaying',
      component: Nowplaying
    },
    {
      path: '/films/comingsoon',
      component: Comingsoon
    },
    {
      path: '/films',
      redirect: '/films/nowplaying'
    }
    ]
  },
  {
    name: 'kerwinDetail', // 命名路由
    path: '/detail/:myid', // 动态路由
    component: Detail
  },
  {
    path: '/cinemas',
    component: Cinemas
  },
  {
    path: '/cinemas/search',
    component: Search
  },
  {
    path: '/center',
    component: () => import('@/views/Center'), // 路由懒加载
    meta: {
      isKerwinRequired: true
    }
  },
  {
    path: '/order',
    component: () => import('@/views/Order'),
    meta: {
      isKerwinRequired: true
    }
  },

  {
    path: '/login',
    component: Login
  },
  {
    path: '/city',
    component: City
  },

  // 重定向
  {
    path: '*',
    redirect: '/films'
  }

]

const router = new VueRouter({
  mode: 'hash',
  routes
})

// 全局拦截

router.beforeEach((to, from, next) => {
  // console.log(to)
  if (to.meta.isKerwinRequired) {
    // 判断本地存储中是否token
    if (localStorage.getItem('token')) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 可记录是从哪个页面跳转到login的
      })
    }
  } else {
    next()
  }
})

export default router
